import { Ref, ref } from 'vue'
import { usePagination } from '@/hooks/usePagination'
import { defaultsDeep } from 'lodash-es'
import { TableResponseData } from '@/types/interface'
type keyPath = Array<string> | string
interface UseTableOptions {
  path?: {
    data?: keyPath
    total?: keyPath
    page?: string
    size?: string
  }
}

export function useTable<T>(
  api: (params: any) => Promise<ApiResponseData<TableResponseData<T>>>,
  token: string,
  initialParams: object | (() => object) = {},
  options?: UseTableOptions,
  pageSizes = [10, 20, 50, 100]
) {
  const defaultOptions: UseTableOptions = {
    path: { data: 'data', total: 'total', page: 'pageNum', size: 'pageSize' }
  }
  const effectiveOptions = defaultsDeep({}, options, defaultOptions)
  const { pagination, setTotal, setCurrentPage, setPageSize } = usePagination(pageSizes)

  const loading = ref(false)
  const data: Ref<T[]> = ref([])

  const getData = async (customParams: object) => {
    loading.value = true
    try {
      const res = await api({ ...customParams, token })
      if (res.statusCode === '0') {
        data.value = res.data.list
        setTotal(res.data.total)
      } else {
        data.value = []
        setTotal(0)
      }
    } finally {
      loading.value = false
    }
  }

  // 加载数据的方法，已经在之前定义
  const load = async (newParams?: object) => {
    const query = {
      ...(typeof initialParams === 'function' ? initialParams() : initialParams),
      [effectiveOptions.path.page]: pagination.pageNum,
      [effectiveOptions.path.size]: pagination.pageSize,
      ...newParams
    }
    await getData(query)
  }

  // 页码改变时的处理函数
  const handleCurrentChange = (newPage: number) => {
    setCurrentPage(newPage)
    load() // 重新加载数据
  }

  // 页大小改变时的处理函数
  const handleSizeChange = (newSize: number) => {
    setPageSize(newSize)
    setCurrentPage(1) // 页大小改变时通常返回第一页
    load() // 重新加载数据
  }

  return {
    data,
    loading,
    pagination,
    setTotal,
    setCurrentPage,
    setPageSize,
    load,
    handleCurrentChange,
    handleSizeChange
  }
}
